package com.yl.chainStore.control.warehouse

import com.alibaba.fastjson.JSONObject
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.yl.chainStore.common.enums.Status
import com.yl.chainStore.common.enums.TypeEnum
import com.yl.chainStore.control.BaseCtrl
import com.yl.chainStore.entity.warehouse.WarehouseGoodSupplier
import com.yl.chainStore.entity.warehouse.WarehouseOutOrder
import com.yl.chainStore.pojo.vo.warehouse.WarehouseGoodSupplierSelectVo
import com.yl.chainStore.pojo.vo.warehouse.WarehouseOutOrderSelectVo
import com.yl.chainStore.services.warehouse.IWarehouseOutOrderService
import com.yl.chainStore.services.warehouse.IWarehouseService
import com.yl.chainStore.services.IWebCompanyUserService
import com.yl.common.ErrorCode
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import com.yl.common.getContext
import com.yl.users.common.annotations.PermsCode
import com.yl.users.entity.CompanyDept
import com.yl.users.entity.CompanyUser
import com.yl.users.pojo.vo.CompanyDeptSelectVo
import com.yl.users.pojo.vo.CompanyUserSelectVo
import com.yl.users.services.ICompanyDeptService
import com.yl.users.services.ISysCompanyService
import org.springframework.transaction.annotation.Transactional
import org.springframework.transaction.interceptor.TransactionAspectSupport
import org.springframework.web.bind.annotation.*

/**
 * 出库单处理
 */
@RestController
@RequestMapping("warehouse/outOrder")
open class WarehouseOutOrderController(
	private val outOrderService: IWarehouseOutOrderService,
	private val iWarehouseService: IWarehouseService,
	private val iSysCompanyService: ISysCompanyService,
    private val iCompanyDeptService: ICompanyDeptService,
	private val iWebCompanyUserService: IWebCompanyUserService
) : BaseCtrl() {

    /**
     * 分页显示
     */
    @PostMapping("outOrderPage")
    @PermsCode("warehouse:outOrder:list")
    @Transactional
    open fun outOrderPage(@RequestBody order: WarehouseOutOrderSelectVo): ResponseBody {
        return returnSuccess(
            iWarehouseService.outOrderPage(
                Page<WarehouseOutOrder>(order.current, order.size), order
            )
        )
    }

    /**
     * 明细
     */
    @GetMapping("outOrderDetail/{id}")
    @PermsCode("warehouse:outOrder:detail")
    @Transactional
    open fun outOrderDetail(@PathVariable id: Long): ResponseBody {
        val outOrder = outOrderService.getOutOrder(id)
        if(outOrder != null){
            outOrder.details = outOrderService.getOutOrderDetails(id)
        }
        return returnSuccess(outOrder)
    }

    /**
     * 暂存
     */
    @PostMapping("staging")
    @Transactional(rollbackFor = [Exception::class])
    open fun staging(@RequestBody outOrder: WarehouseOutOrder):ResponseBody{
        checkOutLog(outOrder)
        if(outOrder.id != 0L){
            //如果有草稿，删除之前的草稿，新增一个草稿
            outOrderService.deleteOutOrder(outOrder.id)
        }
        outOrder.id = 0L

        val result = iWebCompanyUserService.stagingOutOrder(outOrder)
        if (result.code != ErrorCode.SUCCESS.code) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
            return result
        }
        if(outOrder.details != null){
            var i  = 1
            for(detail in outOrder.details!!){
                detail.outOrderId = outOrder.id
                detail.status = Status.STAGING

                val addOrderDetail = outOrderService.addOrderDetail(detail)
                if (addOrderDetail.code != ErrorCode.SUCCESS.code) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
                    return returnError(ErrorCode.DATA_SAVE_FAILED,"第"+i+"行物品错误："+addOrderDetail.msg)
                }
                i++
            }
        }
        return returnSuccess()
    }

    /**
     * 获取暂存
     */
    @GetMapping("getStaging")
    @Transactional
    open fun getStaging():ResponseBody{
        val outOrder = iWebCompanyUserService.getStagingOutOrder(getContext().userId, getContext().subCompanyId)
        if(outOrder != null){

            outOrder.details = outOrderService.getOutOrderDetails(outOrder.id)
        }
        return returnSuccess(outOrder)
    }

    /**
     * 申请
     */
    @PostMapping("addOutOrder")
    @Transactional(rollbackFor = [Exception::class])
    @PermsCode("warehouse:outOrder:add")
    open fun addOutOrder(@RequestBody order: WarehouseOutOrder): ResponseBody {
        if(order.id != 0L){
            //如果有草稿，删除之前的草稿，
            outOrderService.deleteOutOrder(order.id)
        }
        order.id = 0L
        val checkOutLog = checkOutLog(order)
        if (checkOutLog.code != ErrorCode.SUCCESS.code){
            return checkOutLog
        }
        if(order.details.isNullOrEmpty()){
            return returnError(ErrorCode.PARAM_EMPTY,"请输入入库物品")
        }
        val result = iWarehouseService.addOutOrder(order)
        if (result.code != ErrorCode.SUCCESS.code) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
            return result
        }
        var i  = 1
        for(detail in order.details!!){
            detail.outOrderId = order.id
            if (detail.goodCount == 0) {
                return returnError(ErrorCode.PARAM_EMPTY, "第"+i+"行物品错误:请输入物品数量")
            }
            detail.status = Status.WAIT_AUDIT
            val addOrderDetail = outOrderService.addOrderDetail(detail)
            if (addOrderDetail.code != ErrorCode.SUCCESS.code) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
                return returnError(ErrorCode.DATA_SAVE_FAILED,"第"+i+"行物品错误："+addOrderDetail.msg)
            }
            i++
        }
        return returnSuccess()
    }

    private fun checkOutLog(outOrder: WarehouseOutOrder):ResponseBody{
        when (outOrder.type) {
            TypeEnum.WAREHOUSE_OUT_TYPE_SUPPLIER -> {
                if (outOrder.outTypeObjectId == null) {
                    return returnError(ErrorCode.PARAM_EMPTY, "请选择供应商")
                }
                outOrder.supplierId = outOrder.outTypeObjectId
            }
            TypeEnum.WAREHOUSE_OUT_TYPE_USER -> {
                if (outOrder.outTypeObjectId == null) {
                    return returnError(ErrorCode.PARAM_EMPTY, "请选择退领用户")
                }
                outOrder.outWarehouseUserId = outOrder.outTypeObjectId
            }
            TypeEnum.WAREHOUSE_OUT_TYPE_DEPT -> {
                if (outOrder.outTypeObjectId == null) {
                    return returnError(ErrorCode.PARAM_EMPTY, "请选择退领部门")
                }
                outOrder.outWarehouseDeptId = outOrder.outTypeObjectId
            }
            TypeEnum.OTHER -> {

            }

            else -> {
            }
        }
        return returnSuccess()
    }



    /**
     * 审核通过 确认出库单（执行出库操作）
     */
    @PostMapping("completeOutOrder/{id}")
    @Transactional(rollbackFor = [Exception::class])
    @PermsCode("warehouse:outOrder:audit")
    open fun completeOutOrder(@PathVariable id: Long):ResponseBody{
        val result = outOrderService.completeOutOrder(id)
        if (result.code != ErrorCode.SUCCESS.code) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
        }
        return result
    }

    /**
     * 审核不通过
     */
    @PostMapping("noPassOutOrder/{id}")
    @Transactional(rollbackFor = [Exception::class])
    @PermsCode("warehouse:outOrder:audit")
    open fun noPassOutOrder(@PathVariable id: Long):ResponseBody{
        val result = outOrderService.noPassOutOrder(id)
        if (result.code != ErrorCode.SUCCESS.code) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
        }
        return result
    }

    /**
     * 取消出库（作废）
     */
    @PostMapping("cancelOutOrder/{id}")
    @Transactional(rollbackFor = [Exception::class])
    @PermsCode("warehouse:outOrder:cancel")
    open fun cancelOutOrder(@PathVariable id: Long):ResponseBody{
        val result = outOrderService.cancelOutOrder(id)
        if (result.code != ErrorCode.SUCCESS.code) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
        }
        return result
    }

    /**
     * 获取出库
     */
    @GetMapping("getOutOrderType")
    open fun getOutOrderType(): ResponseBody {
        val list = mutableListOf<Map<String, Any>>()
        list.add(TypeEnum.WAREHOUSE_OUT_TYPE_SUPPLIER.getMap())
        list.add(TypeEnum.WAREHOUSE_OUT_TYPE_DEPT.getMap())
        list.add(TypeEnum.WAREHOUSE_OUT_TYPE_USER.getMap())
        list.add(TypeEnum.WAREHOUSE_OUT_TYPE_ORDER.getMap())
        list.add(TypeEnum.WAREHOUSE_OUT_TYPE_SCRAP.getMap())
        list.add(TypeEnum.WAREHOUSE_OUT_TYPE_SCATTERED.getMap())
        list.add(TypeEnum.OTHER.getMap())
        return returnSuccess(list)
    }

    @PostMapping("getOutOrderTypeObjectListByType")
    @Transactional
    open fun getOutOrderTypeObjectListByType(@RequestBody body: JSONObject): ResponseBody {
        val name = body.getString("name")
        val type = body.getString("type")
        val list = mutableListOf<Map<String, Any>>()
        when (type) {
            TypeEnum.WAREHOUSE_OUT_TYPE_SUPPLIER.typeName -> {
                val vo = WarehouseGoodSupplierSelectVo()
                vo.name = name
                vo.deptId = getContext().subCompanyId
                val page =
                    iWarehouseService.supplierPage(Page<WarehouseGoodSupplier>(1, 10), vo)
                for (item in page.records) {
                    val mutableMapOf = mutableMapOf<String, Any>()
                    mutableMapOf["id"] = item.id
                    mutableMapOf["name"] = item.name
                    list.add(mutableMapOf)
                }
            }
            TypeEnum.WAREHOUSE_OUT_TYPE_USER.typeName -> {
                val companyUserSelectVo = CompanyUserSelectVo(realName = name)
                val page =
                    iCompanyDeptService.getSubCompanyUserPage(Page<CompanyUser>(1, 10), companyUserSelectVo, getContext().subCompanyId)
                for (item in page.records) {
                    val mutableMapOf = mutableMapOf<String, Any>()
                    mutableMapOf["id"] = item.id
                    mutableMapOf["name"] = item.realName
                    list.add(mutableMapOf)
                }
            }
            TypeEnum.WAREHOUSE_OUT_TYPE_DEPT.typeName -> {
                val companyDeptSelectVo = CompanyDeptSelectVo(name = name)

                val page =
                    iCompanyDeptService.getSubCompanyDeptPage(Page<CompanyDept>(1, 10), companyDeptSelectVo)
                for (item in page.records) {
                    val mutableMapOf = mutableMapOf<String, Any>()
                    mutableMapOf["id"] = item.id
                    mutableMapOf["name"] = item.name
                    list.add(mutableMapOf)
                }
            }
            TypeEnum.WAREHOUSE_OUT_TYPE_ORDER.typeName -> {

            }
            else -> {

            }
        }
        return returnSuccess(list)
    }



}
